package com.black.service.service;

import com.alibaba.fastjson2.JSONObject;
import com.black.protocol.ErrorCode;
import com.black.protocol.Response;
import com.black.service.dao.DataDao;
import com.black.service.entity.DataEntity;
import com.black.service.entity.UserEntity;
import com.black.service.util.RedisUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class InfoServiceImpl implements InfoService {

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private DataDao dataDao;

    @Override
    public Response<JSONObject> detail(JSONObject param) {
        String token = param.getString("token");
        if (token == null || token.isEmpty() || redisUtil.getExpireTime(token) <= 0) {
            return Response.fail(ErrorCode.ERROR_TOKEN_INVALID);
        }
        String entityStr = redisUtil.get(token);
        UserEntity entity = JSONObject.parseObject(entityStr, UserEntity.class);
        JSONObject result = new JSONObject();
        DataEntity dataEntity = new DataEntity();
        dataEntity.setAuthor(String.valueOf(entity.getId()));
        List<DataEntity> release = dataDao.getList(dataEntity);
        //TODO collect message
        result.put("user", entity);
        result.put("release", release.size());
        result.put("releaseList", release);
        result.put("collect", 0);
        result.put("message", 0);
        refreshToken(token, entityStr);
        return Response.success(result);
    }

    private void refreshToken(String token, String entity) {
        redisUtil.setWithExpire(token, entity, 1800);
    }
}
